import os
import sys

current_dir = os.path.dirname(os.path.abspath(__file__))
src_dir = os.path.join(current_dir, "src")
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

from preprocess import preprocess
from features import compute_simhash, compute_minhash, hamming_distance
from bert_similarity import compute_bert_similarity
from diff_util import get_token_diff_html_dual

# 阈值设置
SIMHASH_DISTANCE_THRESHOLD = 30
MINHASH_JACCARD_THRESHOLD = 0.05
BERT_SIMILARITY_THRESHOLD = 0.85

def analyze_uploaded_file(uploaded_docx, library_dir, debug=False):
    """
    对上传的 DOCX 文件与文件库中的每个 DOCX 文件进行对比，
    返回详细的比对报告列表，每个报告包含：
        - 库文件名
        - SimHash 距离
        - MinHash Jaccard 相似度
        - BERT 余弦相似度
        - library_text: 用于生成词级 HTML 差异报告
    """
    report_list = []

    # 预处理上传的文件
    user_metadata, user_text = preprocess(uploaded_docx)
    if not user_text:
        print("用户上传的文件没有提取到有效文本")
        return report_list, user_text

    user_simhash = compute_simhash(user_text)
    user_minhash = compute_minhash(user_text)
    
    print("【上传文件预处理】")
    print("元数据：", user_metadata)
    
    # 遍历文件库中所有 DOCX 文件
    for filename in os.listdir(library_dir):
        if filename.lower().endswith(".docx"):
            library_file_path = os.path.join(library_dir, filename)
            try:
                lib_metadata, lib_text = preprocess(library_file_path)
            except Exception as e:
                print(f"处理文件 {filename} 失败：{e}")
                continue

            # 计算特征
            lib_simhash = compute_simhash(lib_text)
            lib_minhash = compute_minhash(lib_text)

            # 相似度指标
            simhash_dist = hamming_distance(user_simhash, lib_simhash)
            jaccard_sim = user_minhash.jaccard(lib_minhash)
            bert_sim = compute_bert_similarity(user_text, lib_text)

            if debug:
                print(f"【调试】文件：{filename}")
                print(f"SimHash 距离: {simhash_dist}")
                print(f"MinHash Jaccard 相似度: {jaccard_sim:.4f}")
                print(f"BERT 相似度: {bert_sim:.4f}")
                print("-" * 40)

            # 按照阈值过滤
            if simhash_dist > SIMHASH_DISTANCE_THRESHOLD:
                continue
            if jaccard_sim < MINHASH_JACCARD_THRESHOLD:
                continue
            if bert_sim < BERT_SIMILARITY_THRESHOLD:
                continue

            # 保存信息
            report = {
                "库文件": filename,
                "SimHash 距离": simhash_dist,
                "MinHash Jaccard 相似度": round(jaccard_sim, 4),
                "BERT 相似度": round(bert_sim, 4),
                "library_text": lib_text
            }
            report_list.append(report)
    
    return report_list, user_text

def main():
    uploaded_docx = "uploaded_file.docx"
    library_dir = "library"
    
    reports, user_text = analyze_uploaded_file(uploaded_docx, library_dir, debug=True)
    
    if reports:
        for report in reports:
            # 使用行级对比生成 HTML 差异报告（不进行分词）
            html_report = get_token_diff_html_dual(user_text, report['library_text'])
            html_filename = f"diff_{report['库文件']}.html"
            with open(html_filename, "w", encoding="utf-8") as f:
                f.write(html_report)
            print(f"差异报告已保存到: {html_filename}")
    else:
        print("未发现与上传文件相似的标准文件。")


if __name__ == "__main__":
    main()